<script setup>
import utils from "../FieldUtil.js"
import { defineProps, computed } from "vue";
const { meta, modelName, vm } = defineProps(["meta", "modelName", "vm"]);
const model = vm.getModel(modelName);
const childs = meta.items || [];

function get_value() {
  let v = utils.get(meta, model);
  if (v == null) {
    for (var i = 0; i < childs.length; i++) {
      let child = childs[i];
      if (utils.get(child, model) == true) {
        v = child.name;
        break;
      }
    }
  }
  return v;
}

const editMode = computed(() => {
  return utils.editMode(meta, model);
});

const displayValue = computed(() => {
  let v = get_value();
  let selItem = null;
  for (var i = 0; i < childs.length; i++) {
    let child = childs[i];
    if (v == child.name) {
      selItem = child;
      break;
    }
  }
  return selItem?.title || "~";
});

const value = computed({
  get() {
    return get_value();
  },
  set(newValue) {
    utils.set(meta, model, newValue);

    childs.forEach(x => {
      utils.set(x, model, newValue == x.name, false);
    });
  }
});

const valueEnums = computed(() => {
  let values = [];
  if (meta.items) {
    meta.items.forEach(x => {
      const { name, title } = x;
      values.push({
        name, title
      })
    });
  }
  return values;
});
</script>

<template>
  <div v-if="editMode">
    <el-radio-group v-model="value">
      <el-radio v-for="item in valueEnums" :value="item.name">
        <el-text>{{ item.title }}</el-text>
      </el-radio>
    </el-radio-group>
  </div>
  <el-text v-else class="m-2">{{ displayValue }}</el-text>
</template>